package com.ikun.yummy.activitys.main.fragment.me;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.google.android.material.tabs.TabLayout;
import com.ikun.yummy.App;
import com.ikun.yummy.R;
import com.ikun.yummy.activitys.details.DetailActivity;
import com.ikun.yummy.activitys.login.LoginActivity;
import com.ikun.yummy.activitys.main.MainActivity;
import com.ikun.yummy.activitys.setting.SettingActivity;
import com.ikun.yummy.adapter.CookListAdapter;
import com.ikun.yummy.bean.CookInfo;
import com.ikun.yummy.bean.FollowInfo;
import com.ikun.yummy.bean.LikeInfo;
import com.ikun.yummy.bean.UserInfo;
import com.ikun.yummy.manager.CommentOpManager;
import com.ikun.yummy.manager.CookOpManager;
import com.ikun.yummy.manager.FollowOPManager;
import com.ikun.yummy.manager.LikeOpManager;
import com.ikun.yummy.manager.UserOpManager;
import com.ikun.yummy.sourceop.op.UserOP;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class MeFragment extends Fragment {
    private MeViewModel meViewModel;
    private CookListAdapter adp;
    private final List<CookInfo> cookList = new ArrayList<>();
    private int nowTab=0;
    private CookOpManager cookOpManager;
    private LikeOpManager likeOpManager;
    private CommentOpManager commentOpManager;
    private TextView followcount;
    private TextView fanscount;
    private FollowOPManager followOPManager;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        meViewModel = new ViewModelProvider(this).get(MeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_me, container, false);

        cookOpManager=new CookOpManager(requireContext());
        likeOpManager=new LikeOpManager(requireContext());
        commentOpManager=new CommentOpManager(requireContext());
        followOPManager=new FollowOPManager(requireContext());

        root.findViewById(R.id.ll_follow).setOnClickListener(v -> {
            MainActivity a = (MainActivity) getActivity();
            assert a != null;
            a.startFrgament(R.id.navigation_follow);
        });
        //监听用户账号数据
        final TextView user = root.findViewById(R.id.me_username);
        meViewModel.getUserName().observe(getViewLifecycleOwner(), user::setText);
        //监听用户头像
        final ImageView img = root.findViewById(R.id.me_image);
        meViewModel.getImg().observe(getViewLifecycleOwner(), s -> {
            if (s.equals("")){
                img.setImageResource(R.drawable.user);
            }else{
                img.setImageBitmap(BitmapFactory.decodeFile(s));
            }
        });
        //点击登录
        root.findViewById(R.id.me_login).setOnClickListener(v -> loginOrSetting());
        TabLayout me_tab = root.findViewById(R.id.me_tab);
        me_tab.addTab(me_tab.newTab().setText("我的作品"));
        me_tab.addTab(me_tab.newTab().setText("我赞过的"));
        me_tab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (Objects.requireNonNull(tab.getText()).toString().equals("我的作品")){
                    nowTab=0;
                    getList(0);
                }else{
                    nowTab=1;
                    getList(1);
                }
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) { }
            @Override
            public void onTabReselected(TabLayout.Tab tab) { }
        });
        ListView list = root.findViewById(R.id.me_list);
        //长按删除当前item
        list.setOnItemLongClickListener((parent, view, position, id) -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage("确认删除吗？");
            builder.setTitle("提示");
            builder.setNeutralButton("取消", null);
            builder.setPositiveButton("确定", (dialogInterface, i) -> {
                CookInfo bean = cookList.get(position);
                //只能删除我的数据
                if (bean.username.equals(App.sp.getString("username", "null"))) {
                    //删菜谱的文件
                    File file=new File(bean.coverimage);
                    file.deleteOnExit();
                    try {
                        JSONObject step=new JSONObject(bean.step);
                        for (int j = 0; j < step.length(); j++) {
                            JSONObject stepBean=step.getJSONObject("step"+j);
                            if (!stepBean.isNull("img")){
                                file=new File(stepBean.getString("img"));
                                file.deleteOnExit();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    //删除点赞表
                    List<LikeInfo> list1 = likeOpManager.query(bean.cookid, null);
                    if (list1!=null&&list1.size()>0){
                        for (LikeInfo l :list1) {
                            likeOpManager.delete(l.likeid);
                        }
                    }
                    //删数据库表cook
                    cookOpManager.delete(bean.cookid);
                    //删除评论表
                    commentOpManager.deleteCommentCookid(bean.cookid);
                    //移除视图，更新适配器
                    cookList.remove(position);
                    adp.notifyDataSetChanged();
                    Toast.makeText(requireContext(),"删除成功",Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(requireContext(),"只能删除自己的作品哟",Toast.LENGTH_SHORT).show();
                }
            }).show();
            return true;
        });
        list.setOnItemClickListener((parent, view, position, id) -> {
            Intent intent=new Intent(requireContext(), DetailActivity.class);
            intent.putExtra("cookid", cookList.get(position).cookid);
            startActivity(intent);
        });
        adp=new CookListAdapter(requireContext(),R.layout.item_cook, cookList,1,(v, cookBean, position)->{
            String username=App.sp.getString("username","null");
            if (!username.equals("null")){//如果登录了就执行下面的点赞
                //获取当前用户的bean
                UserOpManager userOpManager=new UserOpManager(requireContext());
                UserInfo userInfo = userOpManager.queryUser(username);
                if (userInfo.loginstate.equals("1")){//1则登录了,0则没登录
                    if(!cookBean.cookid.equals("")&&!cookBean.username.equals("")){//可能点赞
                        List<LikeInfo> list1 = likeOpManager.query(cookBean.cookid, cookBean.username);
                        String likeid="";
                        if (list1!=null){
                            for (LikeInfo l :list1) {
                                if (l.cookid.equals(cookBean.cookid)&&userInfo.username.equals(l.username)){
                                    likeid=l.likeid;
                                    break;
                                }
                            }
                            if (!likeid.equals("")){
                                cookList.remove(position);
                                likeOpManager.delete(likeid);
                            }else{
                                List<LikeInfo> likeInfo = likeOpManager.insert(new LikeInfo(cookBean.cookid, username, cookBean.username, cookBean.cookname));
                                if (likeInfo!=null&&likeInfo.get(0)!=null){
                                    cookList.get(position).likeid=likeInfo.get(0).likeid;
                                    cookList.get(position).like=true;
                                }
                            }
                        }else{
                            List<LikeInfo> likeInfo = likeOpManager.insert(new LikeInfo(cookBean.cookid, username, cookBean.username, cookBean.cookname));
                            if (likeInfo!=null&&likeInfo.get(0)!=null){
                                cookList.get(position).likeid=likeInfo.get(0).likeid;
                                cookList.get(position).like=true;
                            }
                        }
                    }else{//说明没点赞，insert
                        List<LikeInfo> likeInfo = likeOpManager.insert(new LikeInfo(cookBean.cookid, username, cookBean.username, cookBean.cookname));
                        if (likeInfo!=null&&likeInfo.get(0)!=null){
                            cookList.get(position).likeid=likeInfo.get(0).likeid;
                            cookList.get(position).like=true;
                        }
                    }
                    adp.notifyDataSetChanged();
                }else{
                    Toast.makeText(requireContext(),"登陆后才能点赞",Toast.LENGTH_SHORT).show();
                }
            }else{
                Toast.makeText(requireContext(),"登陆后才能点赞",Toast.LENGTH_SHORT).show();
            }
        });
        list.setAdapter(adp);
        followcount=root.findViewById(R.id.me_followcount);
        fanscount=root.findViewById(R.id.me_fansconut);
        root.findViewById(R.id.me_setting).setOnClickListener(v -> loginOrSetting());
        getList(0);
        return root;
    }
    private void loginOrSetting(){
        UserOP userOP =new UserOP(requireContext());
        String username= App.sp.getString("username","null");
        if (!username.equals("null")){
            UserInfo userInfo = userOP.queryUserByUsername(username);
            if (userInfo.loginstate.equals("1")){
                startActivity(new Intent(requireContext(), SettingActivity.class));
            }else {
                startActivity(new Intent(requireContext(), LoginActivity.class));
            }
        }else {
            startActivity(new Intent(requireContext(), LoginActivity.class));
        }
    }
    private void getList(int type) {//0是我的作品1是我点赞
        cookList.clear();
        List<CookInfo> list = cookOpManager.queryAll();
        String user=App.sp.getString("username","null");
        UserOpManager userOpManager=new UserOpManager(requireContext());
        UserInfo userInfo = userOpManager.queryUser(user);
        if (list!=null){
            for (int i = 0; i < list.size(); i++) {
                CookInfo bean = list.get(i);
                if (type==0&&userInfo.loginstate.equals("1")&&!user.equals("null")&&bean.username.equals(user)){
                    List<LikeInfo> likeInfos=likeOpManager.query(bean.cookid,user);
                    boolean hasLike=false;
                    String likeid1="";
                    if (likeInfos!=null){
                        for (LikeInfo l :likeInfos) {//遍历是否点赞
                            if (l.cookid.equals(bean.cookid)&&l.username.equals(userInfo.username)){//用like表的两个值和bean匹配
                                hasLike=true;
                                likeid1=l.likeid;
                                break;
                            }
                        }
                    }
                    if (hasLike){
                        bean.likeid=likeid1;
                        bean.like=true;
                    }else{
                       bean.like=false;
                    }
                    cookList.add(bean);
                }else if (type==1){
                    List<LikeInfo> likeInfos=likeOpManager.query(bean.cookid,user);
                    if (likeInfos!=null&&!user.equals("null")&&userInfo.loginstate.equals("1")){
                        for (LikeInfo l:likeInfos) {//遍历是否点赞
                            if (l.cookid.equals(bean.cookid) && l.username.equals(userInfo.username)) {//用like表的两个值和bean匹配
                                bean.username=cookOpManager.queryByCookId(l.cookid).username;
                                bean.likeid=l.likeid;
                                bean.like=true;
                                cookList.add(bean);
                                break;
                            }
                        }
                    }
                }
            }
            adp.notifyDataSetChanged();
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        String user=App.sp.getString("username","null");
        if (!user.equals("null")){
            UserOpManager userOpManager=new UserOpManager(requireContext());
            UserInfo userInfo =userOpManager.queryUser(user);
            if (userInfo.loginstate.equals("1")){
                meViewModel.setUsername(userInfo.username);
                meViewModel.setImg(userInfo.userimage);

                int count=0;
                List<FollowInfo> follower = followOPManager.queryFollower(user);
                if (follower!=null){
                    count=follower.size();
                }
                followcount.setText(String.valueOf(count));

                count=0;
                List<FollowInfo> followee = followOPManager.queryFollowee(user);
                if (followee!=null){
                    count=followee.size();
                }
                fanscount.setText(String.valueOf(count));

            }else {
                meViewModel.setUsername("点击登录");
                meViewModel.setImg("");
                fanscount.setText("0");
                followcount.setText("0");
            }
        }else {
            meViewModel.setUsername("点击登录");
            meViewModel.setImg("");
            fanscount.setText("0");
            followcount.setText("0");
        }
        getList(nowTab);
    }
}